# 圖片爬蟲 
import requests as rq
import json
import time
import os
count = 1
 
def crawl(page,dir_):
    global count
    if not os.path.exists('./server./material/'+dir_):
        os.mkdir('./server./material/'+dir_)
    url = 'https://image.baidu.com/search/acjson?'
    header = {
        # 'Referer': 'https://image.baidu.com/search/index?ct=201326592&cl=2&st=-1&lm=-1&nc=1&ie=utf-8&tn=baiduimage&ipn=r&rps=1&pv=&fm=rs4&word',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36'
    }
    param = {
        "tn": "resultjson_com",
        "logid": "11007362803069082764",
        "ipn": "rj",
        "ct": "201326592",
        "is": "",
        "fp": "result",
        "queryWord": dir_,
        "cl": "2",
        "lm": "-1",
        "ie": "utf-8",
        "oe": "utf-8",
        "adpicid": "",
        "st": "-1",
        "z": "",
        "ic": "",
        "hd": "",
        "latest": "",
        "copyright": "",
        "word": dir_,
        "s": "",
        "se": "",
        "tab": "",
        "width": "",
        "height": "",
        "face": "0",
        "istype": "2",
        "qc": "",
        "nc": "1",
        "fr": "",
        "expermode": "",
        "force": "",
        "pn": page,
        "rn": "30",
        "gsm": "1e",
        "1615565977798": "",
    }
    response = rq.get(url, headers=header, params=param)
    result = response.text
    # print(response.status_code)
    j = json.loads(result)
    # print(j)
    img_list = []
    for i in j['data']:
        if 'thumbURL' in i:
            # print(i['thumbURL'])
            img_list.append(i['thumbURL'])
    # print(len(img_list))
 
    for n in img_list:
        r = rq.get(n, headers=header)
        with open(f'./server/material/{dir_}/{count+300}.jpg', 'wb') as f:
            f.write(r.content)
        count += 1
 
 
if __name__ == '__main__':
    for i in range(30, 601, 30):
        t1 = time.time()
        crawl(i,'期末复习')
        t2 = time.time()
        t = t2 - t1
        print('page {0} is over!!!  耗时{1:.2f}秒！'.format(i//30, t))